package com.yc.sole.framework.log;

import cn.hutool.core.util.IdUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author yizuomin
 * @date 2024/1/12 14:20
 **/
@Slf4j
@RequiredArgsConstructor
@WebFilter(urlPatterns = "/api/**")
@Order(3)
@Component
public class TraceIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String traceId = request.getHeader("X-Trace-Id");
            if (traceId == null || traceId.isEmpty()) {
                traceId = IdUtil.fastSimpleUUID();
            }
            TraceIdUtils.setTraceId(traceId);
            chain.doFilter(servletRequest, response);
        } finally {
            TraceIdUtils.clearTraceId();
        }
    }
}
